const path = require('path')
const { getPluginResoucePathByPluginId } = require('../../common/utils/fileUtil')
const { app, BrowserWindow } = require('electron');
const { envConst } = require('../../common/constans/envConstans')
const EnvContext = require('../../common/context/EnvContext');
exports.initHeadlessPluginWin = function (plugin, callback) {
    createWin(plugin, callback)
}


function createWin(plugin, callback) {
    const theWin = EnvContext.getInstance().getBrowserWindow(plugin.pluginId)
    if (theWin) {
        callback()
        return
    }

    let mainHtml = plugin.pluginInfo.main
    let preload = plugin.pluginInfo.preload
    preload = preload ? path.join(getPluginResoucePathByPluginId(plugin.pluginId), preload) : null
    mainHtml = mainHtml ? path.join(getPluginResoucePathByPluginId(plugin.pluginId), mainHtml) : null

    if (envConst.dev()) {
        preload = plugin.pluginInfo.development.preload
        mainHtml = plugin.pluginInfo.development.main
    }

    console.info("initHeadlessPluginWin", preload, mainHtml)

    const windowOptions = {
        frame: false,
        show: false,
        skipTaskbar: true,
        useContentSize: true,
        autoHideMenuBar: true,
        webPreferences: {
            spellcheck: false,
            webSecurity: false,
            enableRemoteModule: true,
            backgroundThrottling: false,
            contextIsolation: true,
            webviewTag: true,
            nodeIntegration: true,
            nodeintegrationinsubframes: true,
            preload: preload
        }

    };
    let mainWindow = new BrowserWindow(windowOptions);

    if (mainHtml.startsWith("http")) {
        mainWindow.loadURL(mainHtml);
    } else {
        mainWindow.loadFile(mainHtml);
    }

    mainWindow.on('closed', () => {
        mainWindow = null
    })

    mainWindow.on('blur', () => {
        app.isPackaged && mainWindow.hide()
    })
    mainWindow.once('ready-to-show', () => {
        mainWindow.webContents.openDevTools({ mode: 'detach' });
        callback()
    })

    EnvContext.getInstance().setBrowserWindow(plugin.pluginId, mainWindow)
}